<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="50%">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="入库单号" prop="stockInNo">
        <el-input v-model="formData.stockInNo" placeholder="请输入入库单号" disabled />
      </el-form-item>
      <el-form-item label="标题" prop="title">
        <el-input v-model="formData.title" placeholder="请输入标题" />
      </el-form-item>
      <!-- <el-form-item label="采购单" prop="purchaseOrderId">
        <el-select v-model="formData.purchaseOrderId" filterable placeholder="请选择采购单">
          <el-option
            v-for="item in purchaseOrderList"
            :key="item.id"
            :label="`${item.orderNo}（${item.userName}）`"
            :value="item.id"
          />
        </el-select>
      </el-form-item> -->
      <el-form-item label="商家" prop="supplier">
        <el-input v-model="formData.supplier" placeholder="请输入商家" />
      </el-form-item>
      <el-form-item label="备注" prop="remarks">
        <el-input v-model="formData.remarks" placeholder="请输入备注" type="textarea" :rows="3" />
      </el-form-item>
    </el-form>
    <!-- 入库明细Tab -->
    <el-tabs v-model="activeTab" class="mt-20px" type="border-card">
      <el-tab-pane label="入库明细" name="items">
        <div class="mb-10px">
          <el-button type="primary" @click="openItemDialog">
            <Icon icon="ep:plus" /> 新增入库明细
          </el-button>
        </div>
        <el-table :data="itemList" v-loading="itemLoading" style="width: 100%">
          <el-table-column label="物料编码" prop="materialCode" />
          <el-table-column label="物料名称" prop="materialName" />
          <el-table-column label="物料类型" prop="materialType">
            <template #default="scope">
              <dict-tag :type="DICT_TYPE.OA_MATERIAL_TYPE" :value="scope.row.materialType" />
            </template>
          </el-table-column>
          <el-table-column label="单位" prop="unitType">
            <template #default="scope">
              <dict-tag :type="DICT_TYPE.OA_ASSET_UNIT" :value="scope.row.unitType" />
            </template>
          </el-table-column>
          <el-table-column label="数量" prop="quantity" />
          <el-table-column label="操作" width="100">
            <template #default="scope">
              <el-button-group>
                <el-button link type="primary" v-show="!scope.row.id" @click="openItemDialog(scope.row, scope.$index)">编辑</el-button>
                <el-button link type="danger" v-show="!scope.row.id" @click="removeItem(scope.$index)">删除</el-button>
              </el-button-group>
            </template>
          </el-table-column>
        </el-table>
        <!-- 新增明细弹窗 -->
        <el-dialog v-model="itemDialogVisible" title="新增入库明细" width="500px">
          <el-form :model="itemForm" :rules="itemFormRules" ref="itemFormRef" label-width="80px">
            <el-form-item label="物料" prop="materialId">
              <el-select 
                v-model="itemForm.materialId" 
                filterable 
                placeholder="请选择物料" 
                @change="handleMaterialChange"
                :reserve-keyword="true"
                :loading="materialLoading"
                remote
                :remote-method="searchMaterials"
              >
                <el-option
                  v-for="item in filteredMaterialList"
                  :key="item.id"
                  :label="item.materialCode + ' - ' + item.materialName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="数量" prop="quantity">
              <el-input-number v-model="itemForm.quantity" :min="1" />
            </el-form-item>
            <el-form-item label="备注" prop="remarks">
              <el-input v-model="itemForm.remarks" placeholder="请输入备注" />
            </el-form-item>
          </el-form>
          <template #footer>
            <el-button @click="itemDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitItemForm">确定</el-button>
          </template>
        </el-dialog>
      </el-tab-pane>
    </el-tabs>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { StockInApi, StockInVO, StockInItemApi,StockInItemVO } from '@/api/oa/stockin'
import { MaterialInfoApi } from '@/api/oa/materialinfo'
import { PurchaseOrderApi, PurchaseOrderVO } from '@/api/oa/purchaseorder'
import { PurchaseOrderItemApi } from '@/api/oa/purchaseorder'
import { DICT_TYPE } from '@/utils/dict'
import type { MaterialInfoVO } from '@/api/oa/materialinfo'
import MaterialInfoSelect from '@/views/oa/materialinfo/MaterialInfoSelect.vue'

/** 入库单主 表单 */
defineOptions({ name: 'StockInForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref<Partial<StockInVO & { itemList?: StockInItemVO[] }>>({
  id: undefined,
  stockInNo: undefined,
  purchaseOrderId: undefined,
  supplier: undefined,
  remarks: undefined,
  creatorName: undefined,
  updaterName: undefined,
  itemList: undefined
})
const formRules = reactive({
  // stockInNo: [{ required: true, message: '入库单号不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref

const activeTab = ref('items')
const itemList = ref<StockInItemVO[]>([])
const itemLoading = ref(false)
const itemDialogVisible = ref(false)
const itemFormRef = ref()
const editIndex = ref<number | null>(null)

const itemForm = reactive<Partial<StockInItemVO>>({
  id: undefined,
  materialId: undefined,
  materialCode: '',
  materialName: '',
  materialType: undefined,
  unitType: undefined,
  quantity: 1,
  remarks: ''
})
const itemFormRules = reactive({
  materialId: [{ required: true, message: '物料不能为空', trigger: 'blur' }],
  quantity: [{ required: true, message: '数量不能为空', trigger: 'blur' }]
})
const materialList = ref<MaterialInfoVO[]>([])
const filteredMaterialList = ref<MaterialInfoVO[]>([])
const materialLoading = ref(false)
const purchaseOrderList = ref<PurchaseOrderVO[]>([])

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  await getPurchaseOrderList()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await StockInApi.getStockIn(id)
      itemList.value = formData.value.itemList || []
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  if (!formRef.value) return
  const valid = await formRef.value.validate()
  if (!valid) return
  if (itemList.value.length === 0) {
    message.error('请至少添加一条采购明细')
    return
  }
  formLoading.value = true
  try {
    
    // 组装提交数据
    // const submitData = { ...formData.value, itemList: itemList.value }
    formData.value.itemList = itemList.value
    let res
    if (formType.value === 'create') {
      res = await StockInApi.createStockIn(formData.value)
      message.success('新增成功')
    } else {
      res = await StockInApi.updateStockIn(formData.value)
      message.success('编辑成功')
    }
    dialogVisible.value = false
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    stockInNo: undefined,
    purchaseOrderId: undefined,
    supplier: undefined,
    remarks: undefined,
    creatorName: undefined,
    updaterName: undefined,
    itemList: undefined
  }
  itemList.value = []
  formRef.value?.resetFields()
}

const openItemDialog = async (row?: any, index?: number) => {
  itemDialogVisible.value = true
  // 加载一些初始物料数据
  await loadInitialMaterials()
  
  if (row && typeof index === 'number') {
    // 编辑
    Object.assign(itemForm, row)
    editIndex.value = index
  } else {
    // 新增
    Object.assign(itemForm, {
      id: undefined,
      materialId: undefined,
      materialCode: '',
      materialName: '',
      materialType: undefined,
      unitType: undefined,
      quantity: 1,
      remarks: ''
    })
    editIndex.value = null
  }
}
const handleMaterialChange = (val: number) => {
  // 从筛选后的物料列表中查找选中的物料
  const material = filteredMaterialList.value.find(item => item.id === val)
  if (material) {
    itemForm.materialId = material.id
    itemForm.remarks = material.remarks
    itemForm.materialCode = material.materialCode
    itemForm.materialName = material.materialName
    itemForm.materialType = material.materialType
    itemForm.unitType = material.unitType
  }
}
const submitItemForm = async () => {
  if (!itemFormRef.value) return
  const valid = await itemFormRef.value.validate()
  if (!valid) return
  const itemData = { ...itemForm }
  if (editIndex.value !== null) {
    // 编辑，保留id
    itemList.value.splice(editIndex.value, 1, itemData)
  } else {
    // 新增
    itemList.value.push(itemData)
  }
  itemDialogVisible.value = false
  editIndex.value = null
  message.success(itemData.id ? '编辑明细成功' : '新增明细成功')
}
const getMaterialList = async () => {
  const res = await MaterialInfoApi.getMaterialInfoPage({ pageNo: 1, pageSize: 100 })
  materialList.value = res.list || []
  filteredMaterialList.value = res.list || []
}

const removeItem = (index: number) => {
  itemList.value.splice(index, 1)
}

const getPurchaseOrderList = async () => {
  const res = await PurchaseOrderApi.getPurchaseOrderPage({ status: 2, pageNo: 1, pageSize: 100 })
  purchaseOrderList.value = res.list || []
}

// 物料筛选方法
const filterMaterials = (query: string) => {
  if (query === '') {
    filteredMaterialList.value = materialList.value
  } else {
    filteredMaterialList.value = materialList.value.filter(item => {
      return item.materialCode.toLowerCase().includes(query.toLowerCase()) ||
             item.materialName.toLowerCase().includes(query.toLowerCase())
    })
  }
}

// 加载初始物料数据
const loadInitialMaterials = async () => {
  materialLoading.value = true
  try {
    const res = await MaterialInfoApi.getMaterialInfoPage({ 
      pageNo: 1, 
      pageSize: 20
    })
    materialList.value = res.list || []
    filteredMaterialList.value = res.list || []
  } catch (error) {
    console.error('加载初始物料失败:', error)
    materialList.value = []
    filteredMaterialList.value = []
  } finally {
    materialLoading.value = false
  }
}

// 远程搜索物料方法
const searchMaterials = async (query: string) => {
  console.log('搜索物料被调用，查询词:', query) // 调试日志
  
  if (query === '') {
    // 如果搜索词为空，加载初始数据
    await loadInitialMaterials()
    return
  }
  
  materialLoading.value = true
  try {
    // 同时搜索物料编码和物料名称，后端支持模糊搜索
    const res = await MaterialInfoApi.getMaterialInfoPage({ 
      pageNo: 1, 
      pageSize: 50,
      materialCode: query,
      materialName: query
    })
    
    console.log('搜索结果:', res.list?.length || 0, '条') // 调试日志
    materialList.value = res.list || []
    filteredMaterialList.value = res.list || []
  } catch (error) {
    console.error('搜索物料失败:', error)
    materialList.value = []
    filteredMaterialList.value = []
  } finally {
    materialLoading.value = false
  }
}
</script>